package cn.zc.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class PCDeviceCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 获取User-Agent头信息
        String userAgent = request.getHeader("User-Agent");
        String deviceType = getDeviceType(userAgent);

        // 根据设备类型决定是否允许访问
        if ("Mobile".equals(deviceType)) {
            // 不允许移动设备访问
            response.setStatus(403); // 403 Forbidden
            response.getWriter().write("-6");
            return false;
        }
        return true;
    }
    private String getDeviceType(String userAgent) {
        if (userAgent.contains("Mobile") || userAgent.contains("Android") || userAgent.contains("iPhone")) {
            return "Mobile";
        } else {
            return "Desktop";
        }
    }
}